<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchAddBatch, fetchEditBatch } from '@/service/api';
import { $t } from '@/locales';
import {batchStatusOptions,/* enableStatusOptions ,roleIdOptions */} from '@/constants/business';

defineOptions({
  name: 'ManageBatchOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData: Api.SystemManage.Batch | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.batch.addBatch'),
    edit: $t('page.batch.editBatch')
  };
  return titles[props.operateType];
});
type Model = Pick<
  Api.SystemManage.Batch,
  'id' | 'name' |'status'| 'summarizeProblem' | 'summarizeHighlight' | 'summarizeNeedImprove' | 'note' | 'summarizePerson' | 'remark' | 'deleteFlag'|'startTime'|'endTime'
>;
const model = ref(createDefaultModel(props.rowData));

function createDefaultModel(rowData?: Api.SystemManage.Batch | null): Model {
  const defaultValues: Model = {
    id: '1',
    deleteFlag: 1,
    name: '',
    startTime: '2024-12-05 15:30:59',
    endTime: '2024-12-05 15:30:59',
    status: '0111',
    summarizeProblem: '',
    summarizeHighlight: '',
    summarizeNeedImprove: '',
    note: '',
    summarizePerson: '',
    remark: ''
  };
  return { ...defaultValues, ...rowData };
}
// 验证规则 hospName与deleteFlag必填
type RuleKey = Extract<keyof Model, 'name' | 'deleteFlag'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  deleteFlag: defaultRequiredRule,

};

// /** the enabled role options */
// const roleOptions = ref<CommonType.Option<string>[]>([]);
//
// async function getRoleOptions() {
//   const { error, data } = await fetchGetAllRoles();
//
//   if (!error) {
//     const options = data.map(item => ({
//       label: item.roleName,
//       value: item.roleCode
//     }));
//
//     // the mock data does not have the roleCode, so fill it
//     // if the real request, remove the following code
//     // const userRoleOptions = model.value.userRoles.map(item => ({
//     //   label: item,
//     //   value: item
//     // }));
//     // end
//
//     roleOptions.value = [...userRoleOptions, ...options];
//   }
// }

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  console.log(props.rowData);
  try {
    // 验证表单
    await validate();
    // 根据操作类型构造请求参数
    const params = {
      ...model.value
    };
    let response;
    const { id, ...restParams } = params;
    // 根据操作类型调用不同的接口
    switch (props.operateType) {
      case 'add':
        // 调用添加接口
        console.log(params);
        response = await fetchAddBatch(restParams);
        break;
      case 'edit':
        console.log(params);
        response = await fetchEditBatch(params);
        break;
      default:
        throw new Error('未知的操作类型');
    }
    console.log(response);
    // 根据接口返回结果处理
    if (response.error) {
      window.$message?.error($t('common.operationFailed'));
      return;
    }
    // 提示成功
    window.$message?.success($t('common.updateSuccess'));
    // 关闭抽屉
    closeDrawer();
    // 触发父组件的事件，通知更新表格数据
    emit('submitted');
  } catch (error) {
    // 捕获可能的错误
    console.error('Submit Error:', error);
    // 根据错误类型显示不同的提示
    const errorMessage = $t('common.operationFailed');
    window.$message?.error(errorMessage);
  }
}
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>
<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <template v-if="props.operateType === 'edit'">
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem :label="$t('page.batch.name')">
            <NInput v-model:value="model.name" :placeholder="$t('page.batch.name')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.startTime')">
            <NDatePicker
              v-model:formatted-value="model.startTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('page.batch.startTime')"
              type="datetime"
            />
          </NFormItem>
          <NFormItem :label="$t('page.batch.endTime')">
            <NDatePicker
              v-model:formatted-value="model.endTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('page.batch.endTime')"
              type="datetime"
            />
          </NFormItem>
          <NFormItem :label="$t('page.batch.summarizeProblem')">
            <NInput v-model:value="model.summarizeProblem" :placeholder="$t('page.batch.summarizeProblem')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.summarizeHighlight')">
            <NInput v-model:value="model.summarizeHighlight" :placeholder="$t('page.batch.summarizeHighlight')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.summarizeNeedImprove')">
            <NInput v-model:value="model.summarizeNeedImprove" :placeholder="$t('page.batch.summarizeNeedImprove')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.note')">
            <NInput v-model:value="model.note" :placeholder="$t('page.batch.note')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.summarizePerson')">
            <NInput v-model:value="model.summarizePerson" :placeholder="$t('page.batch.summarizePerson')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.remark')">
            <NInput v-model:value="model.remark" :placeholder="$t('page.batch.remark')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.status')">
            <NSelect
              v-model:value="model.status"
              :options="batchStatusOptions"
              :placeholder="$t('page.batch.status')"
            />
          </NFormItem>
        </NForm>
      </template>
      <template v-else-if="props.operateType === 'add'">
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem :label="$t('page.batch.name')">
            <NInput v-model:value="model.name" :placeholder="$t('page.batch.name')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.hosp')">
            <NSelect
              v-model:value="model.status"
              :options="batchStatusOptions"
              :placeholder="$t('page.batch.status')"
            />
          </NFormItem>
          <NFormItem :label="$t('page.batch.startTime')">
            <NDatePicker
              v-model:formatted-value="model.startTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('page.batch.startTime')"
              type="datetime"
            />
          </NFormItem>
          <NFormItem :label="$t('page.batch.endTime')">
            <NDatePicker
              v-model:formatted-value="model.endTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('page.batch.endTime')"
              type="datetime"
            />
          </NFormItem>
          <NFormItem :label="$t('page.batch.status')">
            <NSelect
              v-model:value="model.status"
              :options="batchStatusOptions"
              :placeholder="$t('page.batch.status')"
            />
          </NFormItem>
        </NForm>
      </template>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
